<template>
  <div>
    <!-- 授权钥匙选择对话框 -->
    <el-dialog :title="'授权钥匙'" :visible.sync="isShow" width="400px" append-to-body>
      <img src="@/assets/images/lxkp_bg_new.897e2d12.png" width="350px" style="margin: 5px; cursor: pointer;"
        @click="clickCard" />
     <img src="@/assets/images/offline_password_img_new.png" width="350px"
        style="margin: 5px; cursor: pointer;" @click="clickCustom" />
    </el-dialog>

    <!-- 授权钥匙对话框 -->
    <el-dialog :title="title" :visible.sync="showCustom" v-if="showCustom" width="900px" append-to-body
      :show-close="false">
      <el-form ref="keyForm" :model="keyForm" :rules="rulesNEW" label-width="80px">
        <!-- 基本信息区域 -->
        <div style="margin-bottom: 20px;">
          <h4 style="margin-bottom: 15px;">基本信息</h4>
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName" label-width="80px" style="width: 320px;">
                <el-input v-model="keyForm.userName" placeholder="请输入住户名" :disabled="keyForm.relation === '0'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学工号" prop="userPhone" label-width="80px" style="width: 320px;">
                <el-input v-model="keyForm.userPhone" placeholder="请输入住户电话" :disabled="keyForm.relation === '0'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="类别" prop="relation" label-width="80px" style="width: 320px;">
                <el-select v-model="keyForm.relation" placeholder="请选择" @change="handleRelationChange">
                  <el-option
                    v-for="dict in dict.type.relation"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div style="float: left;">
                <el-form-item label="密码" prop="password" label-width="80px" style="width: 320px;" v-if="radioType == '1'">
                  <el-input
                    type="number"
                    v-model="keyForm.password"
                    placeholder="请输入6位数密码（不能以0开头）"
                    minlength="6"
                    maxlength="6"
                    :key="'password-input-' + radioType"
                  />
                  <div class="input-hint">密码必须是6位数字，且首位不能为0，不能使用连续数字（如123456或654321）</div>
                </el-form-item>

                <el-form-item label="卡片" prop="password"  label-width="80px" style="width: 320px;" v-if="radioType == '2'">
                  <el-input type="text" disabled v-model="keyForm.password" placeholder="请输入卡号" maxlength="20" />
                </el-form-item>
              </div>
            </el-col>

          </el-row>

        </div>

        <el-row>

<!--
          <el-col :span="12">
            <div style="float: left;margin-left: 20px;">
              <el-form-item label="开始时间" prop="startTime" label-width="100px">
                <el-date-picker clearable v-model="keyForm.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                  :default-time="defaultTime" placeholder="请选择开始时间" @change="start">
                </el-date-picker>
              </el-form-item>
              <div style="margin: 20px">
                <el-radio-group v-model="radio" size="medium" class="radio-group" @change="handleRadioChange">
                  <el-radio-button label="1周"></el-radio-button>
                  <el-radio-button label="3周"></el-radio-button>
                  <el-radio-button label="1月"></el-radio-button>
                  <el-radio-button label="2月"></el-radio-button>
                  <el-radio-button label="3月"></el-radio-button>
                  <el-radio-button label="6月"></el-radio-button>
                  <el-radio-button label="1年"></el-radio-button>
                  <el-radio-button label="2年"></el-radio-button>
                  <el-radio-button label="3年"></el-radio-button>
                  <el-radio-button label="5年"></el-radio-button>
                </el-radio-group>
              </div>
              <el-form-item label="结束时间" prop="endTime" label-width="100px">
                <el-date-picker clearable v-model="keyForm.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                  :default-time="defaultTime" :picker-options="endPickerOptions" placeholder="请选择结束时间">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col> -->
        </el-row>

        <div style="margin: -3px 0px -26px 3px;">
          <p>已授权密码：（添加成功后第一次使用该密码<span style="color: red;">按9#后</span>密码生效或等待24小时之后自动生效）</p>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitFormRuzhu">确 定</el-button>
        <el-button @click="cancelKey">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    tenantToKey
  } from "@/api/lock/tenantUser";
  import {
    addTenantkey,
    updateTenantkey
  } from "@/api/lock/tenantkey";

  // 定义一个独立的 formatDateTime 函数
  function formatDateTime(dateTimeStr) {
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    const hours = ('0' + date.getHours()).slice(-2);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  export default {
    name: "KeyAuth",
    dicts: ['relation'],
    data() {
      return {
        tenantInfo:{},
        // 是否显示授权钥匙选择对话框
        isShow: false,
        // 是否显示授权钥匙详情对话框
        showCustom: false,
        // 标题
        title: "",
        // 钥匙类型（1：密码，2：卡片）
        radioType: '1',
        // 是否显示刷卡区域
        showka: true,
        // 时间选择
        radio: null,
        // 钥匙表单
        keyForm: {},
        // 表单校验规则
        rulesNEW: {
          startTime: [{
            required: true,
            message: '请选择开始时间',
            trigger: 'blur'
          }],
          endTime: [{
            required: true,
            message: '请选择结束时间',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入密码或卡号',
            trigger: 'blur'
          }],
          relation: [{
            required: true,
            message: '请选择关系',
            trigger: 'change'
          }],
          userName: [{
            required: true,
            message: '请输入住户名',
            trigger: 'blur'
          }],
          userPhone: [{
            required: true,
            message: '请输入住户电话',
            trigger: 'blur'
          }]
        }
      };
    },
    computed: {
      endPickerOptions() {
        return {
          disabledDate: time => {
            const startTime = new Date(this.keyForm.startTime).setHours(0, 0, 0, 0);
            const currentDate = new Date().setHours(0, 0, 0, 0);
            return time.getTime() < startTime - 86400000 || time.getTime() < currentDate;
          }
        };
      },
      defaultTime() {
        return '00:00:00';
      }
    },
    created() {
      // 不再需要手动获取关系字典数据
    },
    methods: {
      // 关系变更处理
      handleRelationChange(value) {
        console.log("关系变更为:", value);
        console.log("当前人员信息:", this.tenantInfo);

        if (value === '0') {
          // 获取人员电话 - 检查可能的字段名
          const tenanuserPhone = this.tenantInfo.phone || this.tenantInfo.mobile || this.tenantInfo.phoneNumber || '';

          // 如果是本人，自动填充信息
          this.keyForm.userName = this.tenantInfo.name || '';
          this.keyForm.userPhone = tenanuserPhone;

          console.log("自动填充本人信息:", {
            name: this.keyForm.userName,
            phone: this.keyForm.userPhone
          });
        } else {
          // 如果不是本人，清空信息
          this.keyForm.userName = '';
          this.keyForm.userPhone = '';
        }
      },

      // 显示授权钥匙对话框
      showDialog(tenantInfo) {
        this.isShow = true;
        this.title = "授权钥匙";
        this.tenantInfo = tenantInfo;
        // 打印完整的tenant信息，检查属性
        console.log("钥匙数据(完整):", tenantInfo);

        // 重置密码和卡号值
        this.passwordValue = '';
        this.cardValue = '';

        // 设置默认时间
        this.setDefaultTimes();

        // 设置默认类型为密码授权
        this.radioType = tenantInfo.type || '1';  // 如果有类型则使用已有类型，否则默认为1（密码）

        // 判断是否是编辑钥匙操作
        const isEditKey = tenantInfo.keyId !== undefined;

        // 获取人员电话 - 检查可能的字段名
        const tenanuserPhone = tenantInfo.phone || tenantInfo.mobile || tenantInfo.phoneNumber || '';
        console.log("人员电话信息:", {
          phone: tenantInfo.phone,
          mobile: tenantInfo.mobile,
          phoneNumber: tenantInfo.phoneNumber,
          selected: tenanuserPhone
        });

        // 设置其他表单字段
        this.keyForm = {
          // 如果是编辑钥匙，则设置id字段
          id: isEditKey ? tenantInfo.keyId : undefined,
          userId: tenantInfo.userId || tenantInfo.id,
          tenantId: tenantInfo.tenantId || tenantInfo.id,
          homeId: tenantInfo.homeId,
          cellId: tenantInfo.cellId,
          unitId: tenantInfo.unitId,
          floorId: tenantInfo.floorId,
          idCardNumber: tenantInfo.idCardNumber,
          remark: tenantInfo.remark || tenantInfo.name,
          password: tenantInfo.password || '',
          startTime: tenantInfo.startTime || this.keyForm.startTime,
          endTime: tenantInfo.endTime || this.keyForm.endTime,
          // 强制默认关系为本人
          relation: tenantInfo.relation || '0',
          // 自动填充本人信息
          userName: tenantInfo.userName || tenantInfo.name || '',
          userPhone: tenantInfo.userPhone || tenanuserPhone
        };

        // 如果默认为本人关系，确保填充住户本人信息
        if (this.keyForm.relation === '0') {
          this.keyForm.userName = tenantInfo.name || '';
          this.keyForm.userPhone = tenanuserPhone;
        }

        // 如果是编辑模式，根据类型保存对应的密码或卡号值
        if (tenantInfo.password) {
          if (tenantInfo.type === '1') {
            this.passwordValue = tenantInfo.password;
          } else if (tenantInfo.type === '2') {
            this.cardValue = tenantInfo.password;
          }
        }

        // 新增：如果类型为卡片且有cardNo，自动赋值卡号
        if ((tenantInfo.type === '2' || this.radioType === '2') && tenantInfo.cardNo) {
          this.keyForm.password = tenantInfo.cardNo;
          this.cardValue = tenantInfo.cardNo;
        }

        // 默认选中"1月"单选按钮
        this.radio = "1月";
      },

      // 卡片授权
      clickCard() {
        this.showCustom = true;
        // 在切换类型前，保存当前的值
        if (this.radioType === '1' && this.keyForm.password) {
          this.passwordValue = this.keyForm.password;
        }

        // 切换到卡片类型
        this.radioType = '2';  // '2' 表示卡片类型
        this.title = "离线卡片授权";

        // 设置默认时间
        this.setDefaultTimes();

        // 优先使用tenantInfo.cardNo自动带入卡号
        this.$nextTick(() => {
          if (this.tenantInfo && this.tenantInfo.cardNo) {
            this.keyForm.password = this.tenantInfo.cardNo;
            this.cardValue = this.tenantInfo.cardNo;
          } else {
            this.keyForm.password = this.cardValue;
          }
        });

        // 默认选中"1月"单选按钮
        this.radio = "1月";
      },

      // 密码授权
      clickCustom() {
        this.showCustom = true;

        // 在切换类型前，保存当前的值
        if (this.radioType === '2' && this.keyForm.password) {
          this.cardValue = this.keyForm.password;
        }

        // 切换到密码类型
        this.radioType = '1';  // '1' 表示密码类型
        this.title = "离线密码授权";

        // 设置默认时间
        this.setDefaultTimes();

        // 从缓存恢复密码值
        this.$nextTick(() => {
          this.keyForm.password = this.passwordValue;
        });

        // 默认选中"1月"单选按钮
        this.radio = "1月";
      },

      // 设置默认开始和结束时间
      setDefaultTimes() {
        // 设置开始时间为当前日期时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const currentDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

        // 设置默认结束时间为一个月后
        const endDate = new Date(now);
        endDate.setMonth(now.getMonth() + 1);
        const endYear = endDate.getFullYear();
        const endMonth = String(endDate.getMonth() + 1).padStart(2, '0');
        const endDay = String(endDate.getDate()).padStart(2, '0');
        const endDateTime = `${endYear}-${endMonth}-${endDay} ${hours}:${minutes}:${seconds}`;

        // 如果keyForm不存在，初始化它，但保留现有值
        if (!this.keyForm) {
          this.keyForm = {};
        }

        // 只设置开始和结束时间，不修改其他字段
        this.keyForm.startTime = currentDateTime;
        this.keyForm.endTime = endDateTime;
      },

      // 取消钥匙授权
      cancelKey() {
        this.showCustom = false;
        this.isShow = false;
        this.keyForm = {
          password: ""
        };
      },

      // 开始时间变更
      start() {
        // 如果没有设置结束时间，自动设置为开始时间后一个月
        if (!this.keyForm.endTime && this.keyForm.startTime) {
          const startDate = new Date(this.keyForm.startTime);
          const endDate = new Date(startDate);
          endDate.setMonth(startDate.getMonth() + 1);

          // 格式化日期
          const endYear = endDate.getFullYear();
          const endMonth = String(endDate.getMonth() + 1).padStart(2, '0');
          const endDay = String(endDate.getDate()).padStart(2, '0');
          const endHours = String(endDate.getHours()).padStart(2, '0');
          const endMinutes = String(endDate.getMinutes()).padStart(2, '0');
          const endSeconds = String(endDate.getSeconds()).padStart(2, '0');

          this.keyForm.endTime = `${endYear}-${endMonth}-${endDay} ${endHours}:${endMinutes}:${endSeconds}`;
        }

        // 原有逻辑：如果已选择时间周期，则再次计算结束时间
        if (this.radio != null) {
          this.handleRadioChange(this.radio);
        }
      },

      // 时间周期选择
      handleRadioChange(value) {
        const startDate = new Date(this.keyForm.startTime);
        let endDate = new Date(startDate);

        if (value.includes('周')) {
          const weeks = parseInt(value);
          endDate.setDate(startDate.getDate() + (weeks * 7));
        } else if (value.includes('月')) {
          const months = parseInt(value);
          endDate.setMonth(startDate.getMonth() + months);
        } else if (value.includes('年')) {
          const years = parseInt(value);
          endDate.setFullYear(startDate.getFullYear() + years);
        }

        this.keyForm.endTime = endDate;
      },

      // 提交钥匙授权
      submitFormRuzhu() {
        // 确保有结束时间
        if (!this.keyForm.endTime && this.keyForm.startTime) {
          const startDate = new Date(this.keyForm.startTime);
          const endDate = new Date(startDate);
          endDate.setMonth(startDate.getMonth() + 1);
          this.keyForm.endTime = formatDateTime(endDate);
        }

        // 调试输出 keyForm 的值
        console.log("表单提交前 keyForm 的值:", {
          relation: this.keyForm.relation,
          userName: this.keyForm.userName,
          userPhone: this.keyForm.userPhone,
          type: this.radioType,
          password: this.keyForm.password
        });

        this.$refs["keyForm"].validate(valid => {
          if (valid) {
            // 验证密码/卡号是否存在且有效
            if (!this.keyForm.password || this.keyForm.password.trim() === "") {
              this.$message.error(this.radioType === '1' ? '请输入密码' : '请输入卡号');
              return;
            }

            // 当选择密码授权时，验证密码必须是6位数
            if (this.radioType === '1') {
              if (this.keyForm.password.length !== 6) {
                this.$message.error('密码必须是6位数');
                return;
              }

              // 验证密码开头不能为0
              if (this.keyForm.password[0] === '0') {
                this.$message.error('密码开头不能为0');
                return;
              }

              // 验证密码不能是连续数字
              let isConsecutive = true;
              for (let i = 0; i < this.keyForm.password.length - 1; i++) {
                if (Math.abs(parseInt(this.keyForm.password[i]) - parseInt(this.keyForm.password[i + 1])) !== 1) {
                  isConsecutive = false;
                  break;
                }
              }
              if (isConsecutive) {
                this.$message.error('密码不能是连续的数字序列，如123456或654321');
                return;
              }
            }

            // 验证密码格式
            if (this.keyForm.password) {
              if (this.keyForm.password.includes('-')) {
                this.$message.error('密码不能包含符号');
                return;
              }
            }

            // 根据当前类型保存值到对应变量
            if (this.radioType === '1') {
              this.passwordValue = this.keyForm.password;
            } else {
              this.cardValue = this.keyForm.password;
            }
            // 准备提交的数据 - 确保使用正确的字段名称
            const submitData = {
              ...this.keyForm,
              type: this.radioType, // radioType的值已经是正确的类型码：'1'表示密码，'2'表示卡片
              endTime: formatDateTime(this.keyForm.endTime),
              userName: this.keyForm.userName,
              relationName: this.keyForm.userName,
              userPhone: this.keyForm.userPhone,
              cardNo: this.radioType === '2' ? this.keyForm.password : undefined // 只在卡片类型时传递cardNo
            };

            console.log("提交数据：", submitData); // 调试用，查看提交的数据

            // 检查是否有钥匙ID，如果有则是修改操作，否则是新增操作
            if (submitData.id) {
              updateTenantkey(submitData).then(response => {
                this.$modal.msgSuccess(response.msg || "修改成功");
                this.isShow = false;
                this.showCustom = false;
                this.$emit('refresh');
              });
            } else {
              addTenantkey(submitData).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.isShow = false;
                this.showCustom = false;
                this.$emit('refresh');
              });
            }
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }

  .input-hint {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    line-height: 1.2;
  }
</style>
